import { Injectable } from '@nestjs/common';
import { CreateQustionDto } from './dto/create-qustion.dto';
import { UpdateQustionDto, UpdateSingleQuestionDto } from './dto/update-qustion.dto';
import { PrismaService } from '../prisma/prisma.service';
import * as Mock from 'mockjs';
import { FindQuestionDto } from './dto/find-question.dto';
const Random = Mock.Random;
@Injectable()
export class QustionService {
  constructor(private readonly prisma: PrismaService) {}
  //创建模拟问卷列表数据
  async createMockQuestiona(createMockDto) {
    try {
      const mockData = Array.from({ length: createMockDto.len }, () => {
        return {
          title: Random.ctitle(5, 6),
          answerCount: Math.floor(Math.random() * 100),
          isPublished: Random.boolean(),
          isStar: Random.boolean(),
          isDeleted: Random.boolean(),
        };
      });
      await this.prisma.question.createMany({
        data: mockData,
      });
      return {
        code: 200,
        message: 'success',
      };
    } catch (error) {
      return Promise.reject(error);
    }
  }
  //创建问卷
  async create(userId: number, createQustionDto: CreateQustionDto) {
    const { answerCount, title } = createQustionDto;
    console.log(userId);
    return await this.prisma.question.create({
      data: {
        answerCount: +answerCount,
        title,
        userId: +userId,
        // components: {
        //   create: {
        //     id: uuidv4(),
        //     props: { text: '一级标题', level: 1, isCenter: false },
        //     title: '默认',
        //     type: 'questionTitle',
        //   },
        // },
      },
      // include: { components: true },
    });
  }
  //查找所有question数据
  async findAll(query: FindQuestionDto) {
    try {
      const { keyword, page, pageSize, isDeleted, isPublished, isStar } = query;
      //创建where条件
      const whereConditions = {
        title: { contains: keyword },
        isDeleted: eval(isDeleted),
        isPublished: eval(isPublished),
        isStar: eval(isStar),
      };
      const data = await this.prisma.question.findMany({
        where: whereConditions,
        skip: (page - 1) * pageSize,
        take: Number(pageSize),
      });
      const total = await this.prisma.question.count({
        where: whereConditions,
      });
      return {
        data,
        total,
        page,
        pageSize,
      };
    } catch (error) {
      return Promise.reject(error);
    }
  }
  //查找一条question数据
  async findOne(id: number) {
    return await this.prisma.question.findUnique({
      where: { id },
      include: {
        components: {
          orderBy: { order: 'asc' },
        },
        user: {
          select: { username: true },
        },
      },
    });
  }
  //更新单条Question
  async updateSingleQuestion(id: number, updateQustionDto: UpdateSingleQuestionDto) {
    const { title, description, css, js, answerCount, isDeleted, isPublished, isStar, userId, components } =
      updateQustionDto;
    try {
      // await this.prisma.question.update({   //这种方式只适合components里面有数据的时候
      //   where: {
      //     id,
      //   },
      //   data: {
      //     title,
      //     description,
      //     css,
      //     js,
      //     answerCount,
      //     isDeleted,
      //     isPublished,
      //     isStar,
      //     userId,
      //     components: {
      //       update: components?.map((c) => ({
      //         where: { id: c.id },
      //         data: {
      //           title: c.title,
      //           isHidden: c.isHidden,
      //           isLocked: c.isLocked,
      //           type: c.type,
      //           props: c.props,
      //         },
      //       })),
      //     },
      //   },
      // });
      await this.prisma.question.update({
        where: {
          id,
        },
        data: {
          title,
          description,
          css,
          js,
          answerCount,
          isDeleted,
          isPublished,
          isStar,
          userId,
        },
      });
      await Promise.all(
        components.map((c, index) => {
          return this.prisma.component.upsert({
            where: { id: c.id },
            create: {
              id: c.id,
              props: c.props,
              title: c.title,
              type: c.type,
              isHidden: c.isHidden,
              isLocked: c.isLocked,
              questionId: id,
              order: index + 1,
            },
            update: {
              props: c.props,
              title: c.title,
              type: c.type,
              isHidden: c.isHidden,
              isLocked: c.isLocked,
              order: index + 1,
            },
          });
        }),
      );
      return {
        code: 200,
        success: true,
      };
    } catch (error) {
      return Promise.reject(error);
    }
  }
  //更新多条Question
  async updateBatchQuestion(updateQustionDto: UpdateQustionDto) {
    try {
      const { ids, isDeleted, isStar } = updateQustionDto;
      const data = {
        isDeleted,
        isStar,
      };
      console.log(updateQustionDto);
      await this.prisma.question.updateMany({
        where: {
          id: { in: ids },
        },
        data: data,
      });
      return {
        code: 200,
        success: true,
      };
    } catch (error) {
      return Promise.reject(error);
    }
  }
  remove(id: number) {
    return `This action removes a #${id} qustion`;
  }
}
